#pragma once
#include<iostream>
#include<string>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<fcntl.h>
#include"../Comm/Util.hpp"
#include"../Comm/Log.hpp"
using namespace ns_util;
using namespace ns_log;
class Compiler
{
    public:
    Compiler()
    {}
    //编译成功：返回true 否则：返回false
    static bool Compile(const std::string& file_name)
    {
        int pid=fork();
        if(pid<0)
        {
            LOG(ERROR)<<"创建子进程失败"<<"\n";
            return false;
        }
        else if(pid==0)
        {
            umask(0);
            int _stderr=open(Pathutil::Compile_error(file_name).c_str(),O_WRONLY|O_CREAT,0664);
            if(_stderr<0)
            {
                LOG(ERROR)<<"内部错误,打开stderr文件失败"<<"\n";
                return 0;
            }
            //重定向标准错误，到错误文件中
            dup2(_stderr,2);
            execlp("g++","g++","-o",Pathutil::Exe(file_name).c_str(),Pathutil::Src(file_name).c_str(),"-D","COMPILER_ONLINE","-std=c++11",nullptr/*不要忘了*/)
            LOG(ERROR)<<"程序替换失败"<<"\n";
            exit(1);

        }
        else
        {
            waitpid(pid,nullptr,0);
            if(Fileutil::isExefileEeist(Pathutil::Exe(file_name)))
            {
                LOG(INFO)<<"编译成功..."<<"\n";
                return true;
            }
        }
        LOG(ERROR)<<"编译失败，没有形成可执行"<<"\n";
        return false;
    }
    ~Compiler()
    {}
    private:

};